﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Resources;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;


namespace CommonClass
{
    public class DelegateCommandProperty
    {
        /// <summary>
        /// DelegateCommand 属性改变时，更新界面
        /// </summary>
        /// <param name="vm">ViewModel 基类</param>
        public static void OnDelegateCommandPropertyChanged(NotificationObject vm)
        {
            OnDelegateCommandPropertyChanged<Object>(vm); // Object 只是一个标识
        }


        /// <summary>
        /// DelegateCommand 属性改变时，更新界面
        /// </summary>
        /// <param name="vm">ViewModel 基类</param>
        /// <typeparam name="T">泛型类</typeparam>
        public static void OnDelegateCommandPropertyChanged<T>(NotificationObject vm) where T : class
        {
            PropertyInfo[] propertyInfos = vm.GetType().GetProperties(); // 获得所有属性
            if (propertyInfos == null)
                return;

            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                if (propertyInfo.GetIndexParameters().Length <= 0) // 不是索引器
                {
                    DisplayAttribute displayAttribute =
                        propertyInfo.GetCustomAttributes(typeof(DisplayAttribute),
                        true).Cast<DisplayAttribute>().FirstOrDefault<DisplayAttribute>(); // 获得 Display 属性
                    if (displayAttribute != null &&
                        displayAttribute.GroupName.Equals("DelegateCommand")) // 特定的 GroupName
                    {
                        // 更新界面操作
                        if (typeof(T).Name.Equals("Object")) // 不带泛型参数
                            (propertyInfo.GetValue(vm, null) as DelegateCommand).RaiseCanExecuteChanged(); // 执行指定的方法
                        else
                            (propertyInfo.GetValue(vm, null) as DelegateCommand<T>).RaiseCanExecuteChanged(); // 执行指定的方法
                    }
                }
            }
        }
    }
}
